<template>
  <div class="course-management">
    <h2>{{ $t('message.courseManagement') }}</h2>
    
    <div class="course-actions">
      <el-button type="primary" @click="openAddCourseDialog">{{ $t('message.addCourse') }}</el-button>
    </div>
    
    <el-table
      :data="courses"
      style="width: 100%"
      :default-sort="{ prop: 'createdAt', order: 'descending' }"
      table-layout="fixed"
    >
      <el-table-column :label="$t('message.courseName')" width="200" align="left" header-align="left">
        <template #default="scope">
          <div class="table-cell-content">{{ scope.row.courseName }}</div>
        </template>
      </el-table-column>
      <el-table-column :label="$t('message.subject')" width="120" align="left" header-align="left">
        <template #default="scope">
          <div class="table-cell-content">{{ scope.row.subject }}</div>
        </template>
      </el-table-column>
      <el-table-column :label="$t('message.gradeLevel')" width="120" align="left" header-align="left">
        <template #default="scope">
          <div class="table-cell-content">{{ scope.row.gradeLevel }}</div>
        </template>
      </el-table-column>
      <el-table-column :label="$t('message.duration')" width="100" align="left" header-align="left">
        <template #default="scope">
          <div class="table-cell-content">{{ scope.row.duration }} {{ $t('message.minutes') }}</div>
        </template>
      </el-table-column>
      <el-table-column :label="$t('message.price')" width="100" align="left" header-align="left">
        <template #default="scope">
          <div class="table-cell-content">¥{{ scope.row.price }}</div>
        </template>
      </el-table-column>
      <el-table-column :label="$t('message.maxStudents')" width="120" align="left" header-align="left">
        <template #default="scope">
          <div class="table-cell-content">{{ scope.row.maxStudents }}</div>
        </template>
      </el-table-column>
      <el-table-column :label="$t('message.status')" width="120" align="left" header-align="left">
        <template #default="scope">
          <div class="table-cell-content">
            <el-tag 
              :type="getStatusType(scope.row.status)"
              disable-transitions
            >
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column :label="$t('message.actions')" width="250" align="left" header-align="left">
        <template #default="scope">
          <div class="table-cell-content">
            <el-button size="small" @click="editCourse(scope.row)">{{ $t('message.edit') }}</el-button>
            <el-button size="small" type="success" @click="toggleCourseStatus(scope.row)">{{ getToggleText(scope.row.status) }}</el-button>
            <el-button size="small" type="danger" @click="deleteCourse(scope.row.courseId)">{{ $t('message.delete') }}</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 添加/编辑课程对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
    >
      <el-form :model="courseForm" :rules="courseRules" ref="courseFormRef" label-width="120px">
        <el-form-item :label="$t('message.courseName')" prop="courseName">
          <el-input v-model="courseForm.courseName" :placeholder="$t('message.pleaseEnterCourseName')"></el-input>
        </el-form-item>
        <el-form-item :label="$t('message.courseDescription')" prop="courseDescription">
          <el-input 
            v-model="courseForm.courseDescription" 
            type="textarea"
            :rows="3"
            :placeholder="$t('message.pleaseEnterCourseDescription')"
          ></el-input>
        </el-form-item>
        <el-form-item :label="$t('message.subject')" prop="subject">
          <el-select v-model="courseForm.subject" :placeholder="$t('message.pleaseSelectSubject')" style="width: 100%">
            <el-option
              v-for="subject in subjects"
              :key="subject.value"
              :label="subject.label"
              :value="subject.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('message.gradeLevel')" prop="gradeLevel">
          <el-select v-model="courseForm.gradeLevel" :placeholder="$t('message.pleaseSelectGradeLevel')" style="width: 100%">
            <el-option
              v-for="grade in grades"
              :key="grade.value"
              :label="grade.label"
              :value="grade.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('message.duration')" prop="duration">
          <el-input-number 
            v-model="courseForm.duration" 
            :min="15" 
            :max="300" 
            :step="15"
            :placeholder="$t('message.pleaseEnterDuration')"
          ></el-input-number> {{ $t('message.minutes') }}
        </el-form-item>
        <el-form-item :label="$t('message.price')" prop="price">
          <el-input-number 
            v-model="courseForm.price" 
            :min="0" 
            :precision="2"
            :step="0.01"
            :placeholder="$t('message.pleaseEnterPrice')"
          ></el-input-number> ¥
        </el-form-item>
        <el-form-item :label="$t('message.maxStudents')" prop="maxStudents">
          <el-input-number 
            v-model="courseForm.maxStudents" 
            :min="1" 
            :max="100"
            :placeholder="$t('message.pleaseEnterMaxStudents')"
          ></el-input-number>
        </el-form-item>
        <el-form-item :label="$t('message.status')" prop="status">
          <el-select v-model="courseForm.status" :placeholder="$t('message.pleaseSelectStatus')" style="width: 100%">
            <el-option
              v-for="status in statusOptions"
              :key="status.value"
              :label="status.label"
              :value="status.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">{{ $t('message.cancel') }}</el-button>
          <el-button type="primary" @click="saveCourse">{{ $t('message.confirm') }}</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted, reactive } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useI18n } from 'vue-i18n';
import { useAuthStore } from '@/stores/auth';

export default {
  name: 'CourseManagement',
  setup() {
    const { t } = useI18n();
    const authStore = useAuthStore();
    
    // 课程数据
    const courses = ref([]);
    
    // 对话框相关
    const dialogVisible = ref(false);
    const dialogTitle = ref('');
    const isEdit = ref(false);
    
    // 表单数据
    const courseForm = reactive({
      courseId: '',
      courseName: '',
      courseDescription: '',
      teacherId: '', // 可能需要从当前用户获取
      subject: '',
      gradeLevel: '',
      duration: 60,
      price: 0,
      maxStudents: 1,
      status: 'DRAFT'
    });
    
    const courseFormRef = ref();
    
    // 选项数据
    const subjects = ref([
      { value: 'MATH', label: t('message.math') },
      { value: 'ENGLISH', label: t('message.english') },
      { value: 'CHINESE', label: t('message.chinese') },
      { value: 'PHYSICS', label: t('message.physics') },
      { value: 'CHEMISTRY', label: t('message.chemistry') },
      { value: 'BIOLOGY', label: t('message.biology') },
      { value: 'HISTORY', label: t('message.history') },
      { value: 'GEOGRAPHY', label: t('message.geography') }
    ]);
    
    const grades = ref([
      { value: 'PRIMARY_1', label: t('message.primary1') },
      { value: 'PRIMARY_2', label: t('message.primary2') },
      { value: 'PRIMARY_3', label: t('message.primary3') },
      { value: 'PRIMARY_4', label: t('message.primary4') },
      { value: 'PRIMARY_5', label: t('message.primary5') },
      { value: 'PRIMARY_6', label: t('message.primary6') },
      { value: 'JUNIOR_7', label: t('message.junior7') },
      { value: 'JUNIOR_8', label: t('message.junior8') },
      { value: 'JUNIOR_9', label: t('message.junior9') },
      { value: 'SENIOR_10', label: t('message.senior10') },
      { value: 'SENIOR_11', label: t('message.senior11') },
      { value: 'SENIOR_12', label: t('message.senior12') }
    ]);
    
    const statusOptions = ref([
      { value: 'DRAFT', label: t('message.draft') },
      { value: 'PUBLISHED', label: t('message.published') },
      { value: 'CLOSED', label: t('message.closed') }
    ]);
    
    // 表单验证规则
    const courseRules = {
      courseName: [
        { required: true, message: t('message.pleaseEnterCourseName'), trigger: 'blur' }
      ],
      subject: [
        { required: true, message: t('message.pleaseSelectSubject'), trigger: 'change' }
      ],
      gradeLevel: [
        { required: true, message: t('message.pleaseSelectGradeLevel'), trigger: 'change' }
      ],
      duration: [
        { required: true, message: t('message.pleaseEnterDuration'), trigger: 'blur' }
      ],
      price: [
        { required: true, message: t('message.pleaseEnterPrice'), trigger: 'blur' }
      ],
      maxStudents: [
        { required: true, message: t('message.pleaseEnterMaxStudents'), trigger: 'blur' }
      ]
    };
    
    // 获取课程列表
    const loadCourses = async () => {
      try {
        // 确定是管理员还是教师获取课程
        const isTeacher = authStore.user?.roleId === 'TEACHER';
        const apiUrl = isTeacher 
          ? `/api/teacher/courses` 
          : `/api/admin/courses`;
        
        const response = await fetch(apiUrl, {
          headers: {
            'Authorization': `Bearer ${authStore.token}`,
            'Content-Type': 'application/json'
          }
        });
        
        if (response.ok) {
          const courseData = await response.json();
          
          // 规范化课程数据以确保与表格列定义匹配
          courses.value = courseData.map(course => ({
            courseId: course.courseId || course.course_id || course.id,
            courseName: course.courseName || course.name,
            courseDescription: course.courseDescription || course.description,
            teacherId: course.teacherId || course.teacher_id,
            subject: course.subject,
            gradeLevel: course.gradeLevel || course.grade_level,
            duration: course.duration,
            price: course.price,
            maxStudents: course.maxStudents || course.max_students,
            status: course.status,
            createdAt: course.createdAt || course.created_at || course.create_time,
            updatedAt: course.updatedAt || course.updated_at || course.update_time
          }));
        } else {
          ElMessage.error(t('message.failedToLoadCourses'));
        }
      } catch (error) {
        console.error('Error loading courses:', error);
        ElMessage.error(t('message.failedToLoadCourses'));
      }
    };
    
    // 打开添加课程对话框
    const openAddCourseDialog = () => {
      isEdit.value = false;
      dialogTitle.value = t('message.addCourse');
      resetForm();
      // 如果是教师，自动设置为当前教师ID
      if (authStore.user?.roleId === 'TEACHER') {
        courseForm.teacherId = authStore.user.userId;
      }
      dialogVisible.value = true;
    };
    
    // 编辑课程
    const editCourse = (course) => {
      isEdit.value = true;
      dialogTitle.value = t('message.editCourse');
      // 复制课程数据到表单，确保属性映射正确
      Object.assign(courseForm, {
        courseId: course.courseId || course.course_id || course.id,
        courseName: course.courseName || course.name,
        courseDescription: course.courseDescription || course.description,
        teacherId: course.teacherId || course.teacher_id,
        subject: course.subject,
        gradeLevel: course.gradeLevel || course.grade_level,
        duration: course.duration,
        price: course.price,
        maxStudents: course.maxStudents || course.max_students,
        status: course.status
      });
      dialogVisible.value = true;
    };
    
    // 删除课程
    const deleteCourse = async (courseId) => {
      try {
        await ElMessageBox.confirm(
          t('message.confirmDeleteCourse'),
          t('message.warning'),
          {
            confirmButtonText: t('message.confirm'),
            cancelButtonText: t('message.cancel'),
            type: 'warning'
          }
        );
        
        const response = await fetch(`/api/admin/courses/${courseId}`, {
          method: 'DELETE',
          headers: {
            'Authorization': `Bearer ${authStore.token}`,
            'Content-Type': 'application/json'
          }
        });
        
        if (response.ok) {
          ElMessage.success(t('message.deleteCourseSuccess'));
          loadCourses(); // 重新加载课程
        } else {
          ElMessage.error(t('message.deleteCourseFailed'));
        }
      } catch (error) {
        console.error('Error deleting course:', error);
      }
    };
    
    // 切换课程状态
    const toggleCourseStatus = async (course) => {
      try {
        // 根据当前状态决定下一个状态
        const newStatus = course.status === 'PUBLISHED' ? 'CLOSED' : 'PUBLISHED';
        const actionText = newStatus === 'PUBLISHED' ? t('message.publish') : t('message.close');
        
        await ElMessageBox.confirm(
          `${actionText} ${t('message.courseConfirm')}?`,
          t('message.warning'),
          {
            confirmButtonText: t('message.confirm'),
            cancelButtonText: t('message.cancel'),
            type: 'warning'
          }
        );
        
        // 更新课程状态
        const response = await fetch(`/api/admin/courses/${course.courseId}`, {
          method: 'PUT',
          headers: {
            'Authorization': `Bearer ${authStore.token}`,
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({ ...course, status: newStatus })
        });
        
        if (response.ok) {
          ElMessage.success(`${actionText}${t('message.successSuffix')}`);
          loadCourses(); // 重新加载课程
        } else {
          ElMessage.error(`${actionText}${t('message.failureSuffix')}`);
        }
      } catch (error) {
        console.error('Error toggling course status:', error);
      }
    };
    
    // 保存课程
    const saveCourse = async () => {
      try {
        await courseFormRef.value.validate();
        
        let response;
        if (isEdit.value) {
          // 更新课程
          response = await fetch(`/api/admin/courses/${courseForm.courseId}`, {
            method: 'PUT',
            headers: {
              'Authorization': `Bearer ${authStore.token}`,
              'Content-Type': 'application/json'
            },
            body: JSON.stringify(courseForm)
          });
        } else {
          // 创建课程
          response = await fetch('/api/admin/courses', {
            method: 'POST',
            headers: {
              'Authorization': `Bearer ${authStore.token}`,
              'Content-Type': 'application/json'
            },
            body: JSON.stringify(courseForm)
          });
        }
        
        if (response.ok) {
          ElMessage.success(isEdit.value ? t('message.updateCourseSuccess') : t('message.addCourseSuccess'));
          dialogVisible.value = false;
          loadCourses(); // 重新加载课程
        } else {
          const errorData = await response.json();
          ElMessage.error(errorData.message || (isEdit.value ? t('message.updateCourseFailed') : t('message.addCourseFailed')));
        }
      } catch (error) {
        console.error('Error saving course:', error);
        ElMessage.error(isEdit.value ? t('message.updateCourseFailed') : t('message.addCourseFailed'));
      }
    };
    
    // 重置表单
    const resetForm = () => {
      Object.assign(courseForm, {
        courseId: '',
        courseName: '',
        courseDescription: '',
        teacherId: authStore.user?.roleId === 'TEACHER' ? authStore.user.userId : '',
        subject: '',
        gradeLevel: '',
        duration: 60,
        price: 0,
        maxStudents: 1,
        status: 'DRAFT'
      });
    };
    
    // 获取状态类型（用于标签样式）
    const getStatusType = (status) => {
      switch (status) {
        case 'DRAFT': return 'info';
        case 'PUBLISHED': return 'success';
        case 'CLOSED': return 'danger';
        default: return 'info';
      }
    };
    
    // 获取状态文本
    const getStatusText = (status) => {
      switch (status) {
        case 'DRAFT': return t('message.draft');
        case 'PUBLISHED': return t('message.published');
        case 'CLOSED': return t('message.closed');
        default: return status;
      }
    };
    
    // 获取切换状态按钮文本
    const getToggleText = (status) => {
      return status === 'PUBLISHED' ? t('message.close') : t('message.publish');
    };
    
    onMounted(() => {
      loadCourses();
    });
    
    return {
      courses,
      dialogVisible,
      dialogTitle,
      courseForm,
      courseFormRef,
      courseRules,
      subjects,
      grades,
      statusOptions,
      openAddCourseDialog,
      editCourse,
      deleteCourse,
      toggleCourseStatus,
      saveCourse,
      getStatusType,
      getStatusText,
      getToggleText
    };
  }
};
</script>

<style scoped>
.course-management {
  padding: 20px;
}

.course-actions {
  margin-bottom: 20px;
}

.dialog-footer {
  text-align: right;
}

.table-cell-content {
  text-align: left;
  display: flex;
  align-items: center;
  justify-content: flex-start;
}

/* 确保Element Plus表格内容左对齐 */
:deep(.el-table .cell) {
  text-align: left;
  padding-left: 10px;
}

/* 确保表格内容不会居中对齐 */
:deep(.el-table) {
  table-layout: fixed;
}

:deep(.el-table__body-wrapper) {
  text-align: left;
}
</style>